/**
 * 
 * Copyright (C) 2011 Cody Stoutenburg . All rights reserved.
 *
 *       This program is free software; you can redistribute it and/or
 *       modify it under the terms of the GNU Lesser General Public License
 *       as published by the Free Software Foundation; either version 2.1
 *       of the License, or (at your option) any later version.
 *
 *       This program is distributed in the hope that it will be useful,
 *       but WITHOUT ANY WARRANTY; without even the implied warranty of
 *       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *       GNU Lesser General Public License for more details.
 *
 *       You should have received a copy of the GNU Lesser General Public License
 *       along with this program; if not, write to the Free Software
 *       Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. 
 * 
 */
package ca.usherbrooke.behaviours.world;

import jade.core.AID;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import javax.swing.Timer;

import ca.usherbrooke.agent.message.RequestMessageObjectEntitySubscription;
import ca.usherbrooke.agent.world.BasicWorldAgent;
import ca.usherbrooke.behaviours.BasicCyclicBehaviour;
import ca.usherbrooke.model.world.IWorldModel;

/**
 * @author Cody Stoutenburg
 * 
 */
public class SubscriptionEntityModel extends
		BasicCyclicBehaviour<BasicWorldAgent> {
	private static final long serialVersionUID = 1L;

	public static final int SUBSCRIBER_ENTITY_PERFORMATIVE = ACLMessage.INFORM;

	public static final int SUBSCRIPTION_ENTITY_PERFORMATIVE = ACLMessage.SUBSCRIBE;
	public static final String SUBSCRIPTION_ENTITY_PROTOCOL = "subscribe";

	private static final MessageTemplate TEMPLATE_PERFORMATIVE = MessageTemplate
			.MatchPerformative(SUBSCRIPTION_ENTITY_PERFORMATIVE);
	private static final MessageTemplate TEMPLATE_PROTOCOL = MessageTemplate
			.MatchProtocol(SUBSCRIPTION_ENTITY_PROTOCOL);

	private static final MessageTemplate TEMPLATE_RECEIVE_MESSAGE = MessageTemplate
			.and(TEMPLATE_PERFORMATIVE, TEMPLATE_PROTOCOL);

	private final HashMap<Long, List<AID>> allEntitiesObserver;

	public SubscriptionEntityModel(BasicWorldAgent a) {
		super(a);
		allEntitiesObserver = new HashMap<Long, List<AID>>();

		Timer t = new Timer(100, new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				sendSubscription();
			}
		});
		t.start();
	}

	@SuppressWarnings("unchecked")
	@Override
	public void action() {
		ACLMessage msg = this.getAgent().receive(TEMPLATE_RECEIVE_MESSAGE);

		if (msg != null) {
			Boolean actionDone = false;
			try {
				RequestMessageObjectEntitySubscription<Long> content = (RequestMessageObjectEntitySubscription<Long>) msg
						.getContentObject();

				if (content
						.getRequestType()
						.equals(RequestMessageObjectEntitySubscription.REGISTER_ON_ENTITY)
						|| content
								.getRequestType()
								.equals(RequestMessageObjectEntitySubscription.UNREGISTER_ON_ENTITY)) {
					Long entity = content.getValue();
					if (this.getAgent().getWorld().getEntity(entity) != null) {

						actionDone = true;
						if (!allEntitiesObserver.containsKey(entity)) {
							allEntitiesObserver.put(content.getValue(),
									new ArrayList<AID>());
						}
						List<AID> allObservers = allEntitiesObserver
								.get(entity);

						if (content
								.getRequestType()
								.equals(RequestMessageObjectEntitySubscription.REGISTER_ON_ENTITY)) {
							allObservers.add(msg.getSender());
						} else if (content
								.getRequestType()
								.equals(RequestMessageObjectEntitySubscription.UNREGISTER_ON_ENTITY)) {
							actionDone = true;
							allObservers.remove(msg.getSender());
							if (allObservers.isEmpty()) {
								allEntitiesObserver.remove(entity);
							}
						}
					}
				}
			} catch (UnreadableException ex) {
				ex.printStackTrace();
			}

			if (!actionDone) {
				this.getAgent().putBack(msg);
			}

		} else {
			block();
		}
	}

	protected synchronized ACLMessage prepareMessage(Long id) {
		ACLMessage msg = new ACLMessage(SUBSCRIBER_ENTITY_PERFORMATIVE);
		msg.setProtocol(SUBSCRIPTION_ENTITY_PROTOCOL);

		IWorldModel world = this.getAgent().getWorld().getVision(id);
		try {
			msg.setContentObject(world);
		} catch (IOException ex) {
			ex.printStackTrace();
		}

		return msg;
	}

	private void sendSubscription() {
		for (Entry<Long, List<AID>> entry : this.allEntitiesObserver.entrySet()) {
			ACLMessage msg = prepareMessage(entry.getKey());
			for (AID observer : entry.getValue()) {
				msg.addReceiver(observer);
			}
			this.getAgent().send(msg);
		}
	}
}
